package com.test.config.shiro.jwtConfig;

import com.test.exception.ResultException;
import com.test.util.ApplicationContextUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
@Component
public class JwtFilter extends BasicHttpAuthenticationFilter {

    @SneakyThrows
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.info("~~~~~~~~~~~~~~~~~~~~~~进入了JwtFilter~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        //判断请求的请求头是否带上 "Token"
        String jwtToken = ((HttpServletRequest) request).getHeader("token");
        if (jwtToken != null) {
            //有token,从redis中获取,看是否为已退出用户的token
            RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
            if (redisTemplate.opsForValue().get("logout_" + jwtToken) != null) {
                System.out.println(redisTemplate.opsForValue().get("logout_" + jwtToken));
                System.out.println("退出用户的token在redis中存在");
                String result = ResultException.getResult("400", "token无效");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(result);
            }
            //如果存在，则进入 executeLogin 方法执行登入，检查 token 是否正确
            log.info("token存在");
            try {
                executeLogin(request, response);
                return true;
            } catch (Exception e) {

                /*String result = ResultException.getResult("400", "异常");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(result);*/
                return false;
            }
        }
        //如果请求头不存在 Token，则可能是执行登陆操作或者是游客状态访问，无需检查 token，直接返回 true
        log.info("登录操作,不用校验token");
        return true;
    }

    /**
     * 将非法请求跳转到 /filterError/**中
     */
    private void responseError(ServletResponse response, int code, String message) {
        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            //设置编码，否则中文字符在重定向时会变为空字符串
            message = URLEncoder.encode(message, "UTF-8");
            //如果有项目名称路径记得加上
            httpServletResponse.sendRedirect("/filterError/" + code + "/" + message);

        } catch (IOException e1) {
            log.error(e1.getMessage());
        }
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        log.info("executeLogin ~~~");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("token");
        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;

    }

    //跨域支持
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        log.info("preHandle ~~~");
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }
}
